import { CoolController, BaseController } from '@cool-midway/core';
import { ExpertCommissionEntity } from '../../entity/expertCommission';
import { Body, Inject, Post, Provide } from '@midwayjs/decorator';
import { EXCEL_MAP } from '../../contanst/expertCommission';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { ExpertCommissionService } from '../../service/expertCommission';
import moment = require('moment');

@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: ExpertCommissionEntity,
  listQueryOp: {
    fieldEq: ['data_date'],
    keyWordLikeFields: ['store_name', 'order_number'],
  },
  pageQueryOp: {
    fieldEq: ['data_date'],
    keyWordLikeFields: ['store_name', 'order_number'],
  },
})
export class APIController extends BaseController {
  @InjectEntityModel(ExpertCommissionEntity)
  expertCommissionEntity: Repository<ExpertCommissionEntity>;

  @Inject()
  expertCommissionService: ExpertCommissionService;

  @Post('/import')
  async import(
    @Body('list') data,
    @Body('store_name') store_name,
    @Body('data_date') data_date
  ) {
    const records: any[] = [];
    data.forEach(item => {
      const record: any = {};
      Object.keys(EXCEL_MAP).forEach(key => {
        record[EXCEL_MAP[key]] = item[key]?.replace?.(/\t/g, '') || item[key];
      });
      record.store_name = store_name;
      record.data_date = moment(data_date).format('YYYY-MM-DD');

      records.push(record);
    });

    this.expertCommissionService.upsert(records);
    return this.ok();
  }
}
